﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Framework.Command;
using Framework.Config;
using Microsoft.Practices.Unity;
using Framework.Infrastructure;

namespace Framework.Bus
{
    class CommandBusImpl : ICommandBus
    {
        ISyncBus<ICommand> _SyncCommandBus;
        IAsyncBus<ICommand> _AsyncCommandBus;

        public CommandBusImpl([Dependency(Constants.Configuration.SyncCommandBus)]ISyncBus<ICommand> syncCommandBus
                            , [Dependency(Constants.Configuration.AsyncCommandBus)]IAsyncBus<ICommand> asyncCommandBus = null)
        {
            _SyncCommandBus = syncCommandBus;
            _AsyncCommandBus = asyncCommandBus;
        }

        #region IBus<ICommand> Members

        public void Commit()
        {
            throw new NotSupportedException();
        }

        public void Send<TResult>(ICommand command, Action<TResult> action = null)
        {
            var commandAttr = command.GetType().GetCustomAttribute<CommandAttribute>();
            if (commandAttr != null && commandAttr.Async)
            {
                _AsyncCommandBus.Send(command, action);
            }
            else
            {
                _SyncCommandBus.Send(command);
            }
        }

        public void Send(Command.ICommand command, Action action)
        {
            var commandAttr = command.GetType().GetCustomAttribute<CommandAttribute>();
            if (commandAttr != null && commandAttr.Async)
            {
                _AsyncCommandBus.Send(command, action);
            }
            else
            {
                _SyncCommandBus.Send(command);
            }
        }

        public void Send(Command.ICommand command)
        {
            var commandAttr = command.GetType().GetCustomAttribute<CommandAttribute>();
            if (commandAttr != null && commandAttr.Async)
            {
                _AsyncCommandBus.Send(command);
            }
            else
            {
                _SyncCommandBus.Send(command);
            }
        }

        public void Send(IEnumerable<Command.ICommand> messages)
        {
            messages.ForEach(msg => Send(msg));
        }

        #endregion

        #region IDisposable Members

        public void Dispose()
        {
        }

        #endregion

        #region IBus<ICommand> Members


        public void Publish(ICommand message)
        {
            throw new NotImplementedException();
        }

        public void Publish(IEnumerable<ICommand> messages)
        {
            throw new NotImplementedException();
        }

        #endregion
    }
}
